package net.pimpas.web.jsf.page.controller;

import java.io.Serializable;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public abstract class PageController implements Serializable {
	
	public static final String PAGE_CONTROLLER		= "pageControl";
	private boolean index;

	private static final long serialVersionUID = 8528762789546100063L;
	private Map<String, String> messages;
	private Stack<PageControl> stackNavigation;
	
	public PageController() {
		this.setMessages(new HashMap<String, String>());
		PageControllerManager.getCurrentInstance().loadMessages(this);
		this.setIndex(false);
		this.setStackNavigation(new Stack<PageControl>());
	}
	
	public void pushController( String name ) {
		Class<? extends PageController> pc = null;
		PageControl control = null;
		for(String uri: PageControllerVisitor.pages.keySet()) {
			pc = PageControllerVisitor.pages.get(uri);
			control = pc.getAnnotation(PageControl.class);
			if(control.pageName().equals(name)) {
				this.getStackNavigation().push(control);
				break;
			}
		}
	}
	
	public PageControl pop( ) {
		this.getStackNavigation().firstElement();
		return this.getStackNavigation().remove(0);
	}
	
	public boolean hasMoreElementsInStack( ) {
		return !this.getStackNavigation().isEmpty();
	}
	
	public Map<String, String> getMessages() {
		return messages;
	}
	public void setMessages(Map<String, String> messages) {
		this.messages = messages;
	}
	
	public String getTitle( ) {
		PageControl control = this.getClass().getAnnotation(PageControl.class);
		return this.getMessages().get(control.pageName());
	}
	
	public Integer getYear( ) {
		return Calendar.getInstance().get(Calendar.YEAR);
	}

	public boolean isIndex() {
		return index;
	}

	protected void setIndex(boolean index) {
		this.index = index;
	}

	public Stack<PageControl> getStackNavigation() {
		return stackNavigation;
	}

	private void setStackNavigation(Stack<PageControl> stackNavigation) {
		this.stackNavigation = stackNavigation;
	}
}